using System;
using System.Runtime.InteropServices;
using System.Security.Permissions;
using Microsoft.SharePoint;
using Microsoft.SharePoint.Security;
using Microsoft.SharePoint.Taxonomy.ContentTypeSync;
using System.Collections.Generic;


namespace $safeprojectname$.Features.DeployAndPublish
{
    /// <summary>
    /// This class handles events raised during feature activation, deactivation, installation, uninstallation, and upgrade.
    /// </summary>
    /// <remarks>
    /// The GUID attached to this class may be used during packaging and should not be modified.
    /// </remarks>

    [Guid("$Guid_FeatureRecieverClass_Automation_DeployAndPublish$")]
    public class DeployAndPublishEventReceiver : SPFeatureReceiver
    {

        public override void FeatureActivated(SPFeatureReceiverProperties properties)
        {
            // Setup a collection of the content types to be published
            var contentTypes = new List<SPContentTypeId>();
            contentTypes.Add(new SPContentTypeId("0x010100C568DB52D9D0A14D9B2FDCC96666E9F2007948130EC3DB064584E219954237AF3900$Guid_ContentType_CustomPage$")); // Custom Page
            contentTypes.Add(new SPContentTypeId("0x010100C568DB52D9D0A14D9B2FDCC96666E9F2007948130EC3DB064584E219954237AF3900$Guid_ContentType_CustomPage$00$Guid_ContentType_CustomWelcomePage$")); // Custom Welcome Page
            contentTypes.Add(new SPContentTypeId("0x010100C568DB52D9D0A14D9B2FDCC96666E9F2007948130EC3DB064584E219954237AF3900$Guid_ContentType_CustomPage$00$Guid_ContentType_CustomSitePage$")); // Custom Site Page
            contentTypes.Add(new SPContentTypeId("0x010100C568DB52D9D0A14D9B2FDCC96666E9F2007948130EC3DB064584E219954237AF3900$Guid_ContentType_CustomPage$00$Guid_ContentType_CustomArticlePage$")); // Custom Article Page

            // Connect to the site 
            using (var site = properties.Feature.Parent as SPSite)
            {
                // If Content Type Publishing is enabled from this site then publish the content types in this feature
                if (ContentTypePublisher.IsContentTypeSharingEnabled(site))
                {
                    var publisher = new ContentTypePublisher(site);

                    // Publish the content types
                    foreach (var spContentTypeId in contentTypes)
                    {
                        var cType = site.RootWeb.ContentTypes[spContentTypeId];
                        publisher.Publish(cType);

                        if (!publisher.IsPublished(cType))
                        {
                            // TODO Error handling
                        }
                    }
                }
            }

        }
    }
}